﻿using InfluxData.Net.Common.Enums;
using InfluxData.Net.InfluxDb;
using InfluxData.Net.InfluxDb.Models.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunctionLib.DBOperator
{
    public class InfluxDBClient
    {
        InfluxDbClient clientDb = null;
        string dbName = null;
        public InfluxDBClient() : this("http://localhost:8086/", "admin", "admin", "DBTest")
        {
        }
        public InfluxDBClient(string infuxUrl, string infuxUser, string infuxPwd, string dbName)
        {
            this.clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest);
            this.dbName = dbName;
        }
        public static InfluxDBClient CreatDBClient() 
        {
            return new InfluxDBClient();
        }
        public string[] GetTags(string tagID)
        {
            var res = ExecuteQuery("show tag values from testHis WITH KEY=" + tagID);
            if (res == null || res.Length < 1)
                return new string[]{ };
            for (int i = 0; i < res[0].Columns.Count; i++) 
            {
                if (res[0].Columns[i].Equals("Value",StringComparison.OrdinalIgnoreCase))
                { 
                    return res[0].Values.Select(item => item[i].ToString()).ToArray();
                }
            }
            return new string[] { };

        }
        public Serie[] ExecuteQuery(string query)
        {
            try
            {
                var response = clientDb.Client.QueryAsync(query, this.dbName);
                response.Wait();
                return response.Result.ToArray();
            }
            catch  
            {
                return null;
            }
        }
    }
}
